﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

using GameServer.Virtual_Objects.User;
using GameServer.Networking.Packets;
using GameServer.Managers;

namespace GameServer.Networking.Handlers
{
    class HANDLE_CHARACTER_INFO : PacketHandler
    {
        public override void Handle(virtualUser User)
        {
            try
            {
                //25088 126 -1 Crystaalz Crystaalz 1 0 0 1 -1 -1 -1 -1 0 0 12345roto dnjfhr^
                int UserID = int.Parse(getBlock(0));
                if (BanManager.isBlocked(UserID) == false)
                {
                    string LoginName = getBlock(2);
                    string[] checkData = DB.runReadRow("SELECT id, username, nickname, password FROM users WHERE id='" + UserID + "'");
                    if (checkData.Length > 0)
                    {
                        if (checkData[0] != UserID.ToString()) User.disconnect();
                        if (checkData[1].ToLower() != LoginName.ToLower()) User.disconnect();
                    }
                    else
                        User.disconnect();

                    string[] UserData = DB.runReadRow("SELECT id, username, nickname, exp, dinar, kills, deaths, premium, premiumExpire, cash, rank, coupons, todaycoupon, pc, clanID, clanrank FROM users WHERE id='" + UserID + "' AND username='" + LoginName + "'");
                    if (UserData.Length > 0)
                    {
                        User.UserID = int.Parse(UserData[0]);
                        User.Username = UserData[1];
                        User.Nickname = UserData[2];
                        User.Exp = int.Parse(UserData[3]);
                        User.Dinar = int.Parse(UserData[4]);
                        User.Kills = int.Parse(UserData[5]);
                        User.Deaths = int.Parse(UserData[6]);
                        User.Premium = int.Parse(UserData[7]);
                        User.PremiumExpire = long.Parse(UserData[8]);
                        User.Cash = int.Parse(UserData[9]);
                        User.Rank = int.Parse(UserData[10]);
                        User.Coupons = int.Parse(UserData[11]);
                        User.TodayCoupon = int.Parse(UserData[12]);
                        User.PCItem = (int.Parse(UserData[13]) == 1) ? true : false;
                        User.ClanID = int.Parse(UserData[14]);
                        if (User.Nickname.Contains("[GM]") || User.Nickname.Contains("[MOD]"))
                        {
                            DB.runQuery("UPDATE users SET active = '0' WHERE id=" + User.UserID);
                            User.disconnect();
                        }
                        if (User.Rank > 4) User.Nickname = "[GM]" + User.Nickname;
                        else if (User.Rank > 2) User.Nickname = "[MOD]" + User.Nickname;
                        else if (User.Rank > 1) User.Nickname = "[D]" + User.Nickname;
                        DB.runQuery("UPDATE users SET lasthwid='" + User.HWID + "' WHERE id='" + User.UserID + "'");
                        if (User.ClanID != -1)
                        {
                            User.ClanRank = int.Parse(UserData[15]);
                        }
                        User.uniqID = int.Parse(getBlock(4)); // 1
                        User.uniqID2 = int.Parse(getBlock(5)); // 0
                        User.uniqIDisCRC = int.Parse(getBlock(6)); // 910
                        User.Channel = 1;

                        User.Clan = ClanManager.getClan(User.ClanID);
                        
                        DB.runQuery("UPDATE users SET lasthwid='" + User.HWID + "' WHERE id='" + User.UserID + "'");

                        DateTime current = DateTime.Now;
                        int StartTime = int.Parse(String.Format("{0:yyMMddHH}", current));

                        string[] Skin = DB.runReadRow("SELECT class_0,class_1,class_2,class_3,class_4 FROM users_costumes WHERE ownerid='" + User.UserID + "'");
                        if (Skin.Length > 0)
                        {
                            User.CostumeE = Skin[0];
                            User.CostumeM = Skin[1];
                            User.CostumeS = Skin[2];
                            User.CostumeA = Skin[3];
                            User.CostumeH = Skin[4];
                        }

                        if (User.ClanID != -1)
                        {
                            string[] Clan = DB.runReadRow("SELECT clanname FROM clans WHERE id='" + User.ClanID + "'");
                            if (Clan.Length > 0)
                            {
                                User.ClanName = Clan[0];
                            }
                        }
                        else
                        {
                            DB.runQuery("UPDATE users SET clanID='-1', clanRank='1' WHERE id='" + User.UserID + "'");
                        }

                        bool isEventMessage = false;

                        string[] checkFirstLogin = DB.runReadRow("SELECT firstlogin FROM users WHERE id='" + User.UserID.ToString() + "'");
                        if (checkFirstLogin[0].Equals("2"))
                        {
                            bool toDo = true;
                            if (User.hasItem("DF14") || User.hasItem("CN01") || User.hasItem("DC64") || User.hasItem("DG01"))
                            {
                                toDo = false;
                            }
                            if (toDo == true)
                            {
                                DateTime time2 = DateTime.Now.AddDays(7).AddHours(-1);
                                DateTime ExpireTime2 = DateTime.Now.AddDays(3).AddHours(-1);
                                int num3 = int.Parse(string.Format("{0:yyMMddHH}", time2));
                                int ExpireTime = int.Parse(string.Format("{0:yyMMddHH}", ExpireTime2));
                                DB.runQuery("INSERT INTO inventory (ownerid,expiredate,itemcode) VALUES ('" + User.UserID + "', '" + num3.ToString() + "', 'DB33')");
                                DB.runQuery("INSERT INTO inventory (ownerid,expiredate,itemcode) VALUES ('" + User.UserID + "', '" + num3.ToString() + "', 'DF05')");
                                DB.runQuery("INSERT INTO inventory (ownerid,expiredate,itemcode) VALUES ('" + User.UserID + "', '" + num3.ToString() + "', 'CN01')");
                                DB.runQuery("INSERT INTO inventory (ownerid,expiredate,itemcode) VALUES ('" + User.UserID + "', '" + num3.ToString() + "', 'DC03')");
                                DB.runQuery("INSERT INTO inventory (ownerid,expiredate,itemcode) VALUES ('" + User.UserID + "', '" + num3.ToString() + "', 'DG01')");
                                DB.runQuery("INSERT INTO inventory (ownerid,expiredate,itemcode) VALUES ('" + User.UserID + "', '" + num3.ToString() + "', 'DJ03')");
                                DB.runQuery("INSERT INTO inventory (ownerid,expiredate,itemcode) VALUES ('" + User.UserID + "', '" + num3.ToString() + "', 'CA01')");
                                User.send(new PACKET_SIGN_UP(User));
                            }
                            DB.runQuery("UPDATE users SET firstlogin='1' WHERE id='" + User.UserID + "'");
                        }

                        for (int i = 0; i < 5; i++)
                        {
                            User.cCodes6th[i] = "^";
                        }

                        bool ExpiredWeapon = false;

                        int[] checkCostumeIDs = DB.runReadColumn("SELECT id FROM inventory_costume WHERE ownerid='" + UserID.ToString() + "' AND deleted='0'", 0, null);
                        for (int I = 0; I < checkCostumeIDs.Length; I++)
                        {
                            string[] itemData = DB.runReadRow("SELECT expiredate, itemcode FROM inventory_costume WHERE id=" + checkCostumeIDs[I].ToString());
                            if (int.Parse(itemData[0]) < StartTime)
                            {
                                int InvItems = 0;
                                foreach (CostumeItem _InvItem in User.Costume)
                                {
                                    if (_InvItem != null) InvItems++;
                                }
                                if (InvItems > 30)
                                {
                                    DB.runQuery("DELETE FROM inventory_costume WHERE ownerid='" + UserID.ToString() + "'");
                                    User.send(new PACKET_CHAT("SYSTEM", PACKET_CHAT.ChatType.Room_ToAll, "SYSTEM >> Your inventory was resetted due too many weapons!", 999, "NULL"));
                                    User.Costume = new CostumeItem[35];
                                }
                                DB.runQuery("DELETE FROM inventory_costume WHERE ownerid='" + UserID.ToString() + "' AND itemcode='" + itemData[1] + "'");
                                User.LeftItems.Add(itemData[1]);
                                ExpiredWeapon = true;
                            }
                        }

                        int[] checkItemIDs = DB.runReadColumn("SELECT id FROM inventory WHERE ownerid='" + User.UserID.ToString() + "' AND deleted='0'", 0, null);
                        for (int I = 0; I < checkItemIDs.Length; I++)
                        {
                            string[] itemData = DB.runReadRow("SELECT expiredate, itemcode FROM inventory WHERE id=" + checkItemIDs[I].ToString());
                            if (int.Parse(itemData[0]) < StartTime)
                            {
                                int InvItems = 0;
                                foreach (InventoryItem _InvItem in User.Inventory)
                                {
                                    if (_InvItem != null) InvItems++;
                                }
                                if (InvItems > 30)
                                {
                                    DB.runQuery("DELETE FROM inventory WHERE ownerid='" + User.UserID.ToString() + "'");
                                    User.send(new PACKET_CHAT("SYSTEM", PACKET_CHAT.ChatType.Room_ToAll, "SYSTEM >> Your costume's inventory was resetted due too many weapons!", 999, "NULL"));
                                    User.Inventory = new InventoryItem[35];
                                }
                                DB.runQuery("DELETE FROM inventory WHERE ownerid='" + User.UserID.ToString() + "' AND itemcode='" + itemData[1] + "'");
                                User.LeftItems.Add(itemData[1]);
                                ExpiredWeapon = true;
                            }
                        }

                        int[] costumeIDs = DB.runReadColumn("SELECT id FROM inventory_costume WHERE ownerid ='" + User.UserID.ToString() + "' AND deleted='0'", 0, null);
                        for (int I = 0; I < costumeIDs.Length; I++)
                        {
                            try
                            {
                                string[] itemData = DB.runReadRow("SELECT expiredate, itemcode FROM inventory_costume WHERE id=" + costumeIDs[I].ToString());
                                User.Costume[I] = new CostumeItem(int.Parse(itemData[0]), itemData[1].ToLower());
                            }
                            catch
                            {
                            }
                        }

                        if (Program.ESL)
                        {
                            DateTime _ESLTime = DateTime.Now;
                            _ESLTime = _ESLTime.AddDays(365);
                            _ESLTime = _ESLTime.AddHours(-1);
                            int ESLTime = int.Parse(String.Format("{0:yyMMddHH}", _ESLTime));
                            /*ESL*/
                            User.Inventory[0] = new InventoryItem(ESLTime, "DF95");
                            User.Inventory[1] = new InventoryItem(ESLTime, "DE07");
                            User.Inventory[2] = new InventoryItem(ESLTime, "DG63");
                            User.Inventory[3] = new InventoryItem(ESLTime, "DB63");
                            User.Inventory[4] = new InventoryItem(ESLTime, "DJ13");
                            User.Inventory[5] = new InventoryItem(ESLTime, "DC03");
                            User.Inventory[6] = new InventoryItem(ESLTime, "DC10");
                            User.Inventory[7] = new InventoryItem(ESLTime, "DF03");
                            User.Inventory[8] = new InventoryItem(ESLTime, "DF02");
                            User.Inventory[8] = new InventoryItem(ESLTime, "CA01");
                            User.reloadInventory();
                            /*END*/
                        }

                        int[] itemIDs = DB.runReadColumn("SELECT id FROM inventory WHERE ownerid ='" + User.UserID.ToString() + "' AND deleted='0'", 0, null);
                        for (int I = 0; I < itemIDs.Length; I++)
                        {
                            try
                            {
                                if (Program.ESL == false)
                                {
                                    string[] itemData = DB.runReadRow("SELECT expiredate, itemcode FROM inventory WHERE id=" + itemIDs[I].ToString());
                                    User.Inventory[I] = new InventoryItem(int.Parse(itemData[0]), itemData[1].ToLower());
                                }
                            }
                            catch
                            {
                            }
                        }

                        string[] _CostumeE = User.CostumeE.Split(new char[] { ',' });
                        string[] _CostumeM = User.CostumeM.Split(new char[] { ',' });
                        string[] _CostumeS = User.CostumeS.Split(new char[] { ',' });
                        string[] _CostumeA = User.CostumeA.Split(new char[] { ',' });
                        string[] _CostumeH = User.CostumeH.Split(new char[] { ',' });

                        if (User.hasCostume(_CostumeE[0]) == false) { User.CostumeE = "BA01,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^"; DB.runQuery("UPDATE users_costumes SET class_0='" + User.CostumeE + "' WHERE ownerid='" + UserID + "'"); }
                        if (User.hasCostume(_CostumeM[0]) == false) { User.CostumeM = "BA02,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^"; DB.runQuery("UPDATE users_costumes SET class_1='" + User.CostumeM + "' WHERE ownerid='" + UserID + "'"); }
                        if (User.hasCostume(_CostumeS[0]) == false) { User.CostumeS = "BA03,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^"; DB.runQuery("UPDATE users_costumes SET class_2='" + User.CostumeS + "' WHERE ownerid='" + UserID + "'"); }
                        if (User.hasCostume(_CostumeA[0]) == false) { User.CostumeA = "BA04,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^"; DB.runQuery("UPDATE users_costumes SET class_3='" + User.CostumeA + "' WHERE ownerid='" + UserID + "'"); }
                        if (User.hasCostume(_CostumeH[0]) == false) { User.CostumeH = "BA05,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^,^"; DB.runQuery("UPDATE users_costumes SET class_4='" + User.CostumeH + "' WHERE ownerid='" + UserID + "'"); }

                        bool forcesave = false;
                        string[] equipment = DB.runReadRow("SELECT class0, class1, class2, class3, class4 FROM equipment WHERE ownerid=" + UserID.ToString());
                        for (int I = 0; I < 5; I++)
                        {
                            string[] slotItems = equipment[I].Split(new char[] { ',' });
                            for (int J = 0; J < slotItems.Length; J++)
                            {
                                if (User.hasItem(slotItems[J]) || slotItems[J] == "^" || (slotItems[J] == "DA02" && J == 0) || (slotItems[J] == "DB01" && J == 1)
                            || (slotItems[J] == "DF01" && J == 2 && (I == 0 || I == 1)) || (slotItems[J] == "DG05" && J == 2 && I == 2) || (slotItems[J] == "DC02" && J == 2 && I == 3) || (slotItems[J] == "DJ01" && J == 2 && I == 4)
                            || (slotItems[J] == "DR01" && I == 0 && J == 3) || (slotItems[J] == "DQ01" && I == 1 && J == 3) || (slotItems[J] == "DN01" && (I == 2 || I == 3) && J == 3) || (slotItems[J] == "DL01" && I == 4 && J == 3))
                                {
                                    User.Equipment[I, J] = slotItems[J];
                                }
                                else
                                {
                                    if (slotItems[J].Contains("-") || slotItems[J].Contains("I0"))
                                    {
                                        User.Equipment[I, J] = slotItems[J];
                                    }
                                    else
                                    {
                                        User.Equipment[I, J] = "^";
                                        forcesave = true;
                                    }
                                }
                            }
                        }

                        User.LoadItems(); // Retails && Items
                        
                        /*Login Event*/

                        /*
                         * user.checkrforevent
                            int InvItems = 0;
                            foreach (InventoryItem _InvItem in User.Inventory)
                            {
                                if (_InvItem != null) InvItems++;
                            }

                            //TODO Extend

                            if (StartTime < Convert.ToInt32("13051523"))
                            {
                                if (InvItems >= 3)
                                {
                                    string _Item1 = "DF41";
                                    string _Item2 = "DC61";
                                    string _Item3 = "DG10";
                                    User.AddItem(_Item1, 3);
                                    User.AddItem(_Item2, 3);
                                    User.AddItem(_Item3, 3);
                                    User.send(new PACKET_MESSAGE_BOX("You've_got:_CX4STORM-SW_(3_days),_WA2000_(3_days),_AK47-EX_(3_days)_for_login_event,_event_end's_~15 May"));
                                    DB.runQuery("INSERT INTO users_events (eventid, userid) VALUES ('" + EventID + "','" + User.UserID + "')");
                                }
                                else
                                    User.send(new PACKET_ITEMSHOP(PACKET_ITEMSHOP.ErrorCodes.InventoryFull, "NULL"));
                            }
                        }*/
                        User.PremiumTimeLeft();
                        User.send(new PACKET_CHARACTER_INFO(User));
                        User.send(new PACKET_PING(User));
                        User.send(new PACKET_CLIENT_PACKET(0)); // Welcome sound
                        UserManager.addUser(User);
                        if (isEventMessage == true)
                            User.send(new PACKET_MESSAGE_BOX("Check_your_inventory!_:)"));
                        if (ExpiredWeapon == true)
                        {

                            for (int I = 0; I < 5; I++)
                            {
                                User.Equipment[I, 5] = "^";
                            }
                            User.send(new PACKET_EXPIRE_ITEM(User));
                        }
                        User.send(new PACKET_CREDITS(User));
                    }
                    else
                    {
                        //
                    }
                }
                else
                {
                    User.send(new PACKET_CHARACTER_INFO(73030));
                    User.disconnect();
                }
            }
            catch
            {
                User.disconnect();
            }
        }
    }
}
